Table of Contents

CGI Overview

  • A Typical CGI Interaction
    • Transferring the Form Data
    • Creating Virtual Documents
  • URl Encoding
  • Extra Path Information
  • CGI Environment Variables

The CGI.pm Module

  • HTML Tag Generation
  • Imorting Method Groups
  • Maintaining State
  • Named Parameters
  • Using JavaScript Features
  • Debugging

Overview

The Common Gateway Interface (CGI) is an essential tool for creating and managing comprehensive web sites. With CGI, you can write scripts that create interactive, user-driven applications.

CGI allows the web server to communicate with other programms that are running on the server. For example, with CGI, the web server can invoke an external program, while passing user-specific data to the program (such as what host the user is connecting from, or input the user has supplied through an HTML form). The program then processes that data, and the server passes the program's response back to the web browser.

Rather than limiting the Web to documents written ahead of time, CGI enables web pages to be created on the fly, based upon the input of users. You can also use CGI scripts to create a wide range of applications, from survey to search tools, from Internet service gateways to quizzes and games. You can count the number of users who access a document or let them sign an electronic guest book. You can provide users will all types of information, collect their comments, and respond.

A typical CGI Interaction

For example of a CGI application, suppose you create a guestbook for your web site. The gustbook page asks users to submit their first name and last name using a fill-in form composed of two inout text fields.

The HTML that produces this form might read as follows

<HTML><HEAD><TITLE>Guestbook</TITLE></HEAD>
<BODY>
<H1>Fill in my guestbook</H1>
<FORM METHOD="GET" ACTION="/cgi-bin/guestbook.pl">
<PRE>
First Name: <INPUT TYPE="TEXT" NAME="firstname">
Last Name : <INPUT TYPE="TEXT" NAME="lastname">

<INPUT TYPE="SUBMIT"> <INPUT TYPE="RESET>
</FORM></BODY>

The form is written using special "form" tags:

  • The <form> tag defines the method used for the form (either GET or POST) and the action to take when the form is submitted - that is, the URL of the CGI program to pass the parameters to.

  • The <input> tag can be used in many different ways. In the first two invocations, it creates a text input field and defines the variable name to associate with the field's contents when the form is submitted. The first field is given the variable name "firstname", and the second field is given the name "lastname".

  • In its last two invocations, the <input> tag creates a Submit button and a Reset button

  • The </form> indicates the end of the form.

when the user presses the Submit button, data entered into the <input> text fields is passed to the CGI program specified by the action attribute of the <form> tag (in this case, the /cgi-bin/guestbook.pl program).

Transferring the data

Parameters to a CGI program are transferred either in the URL or in the body text of the request. The method used to pass parameters is determined by the method attribute to <form> tag. The GET method says to transfer data within the URL itself; fo exampl, under the GET method, the web browser might initiate the HTTP transaction as follows:

GET /cgi-bin/guestbook.pl?firstname=Joe&lastname=Grant HTTP/1.0              

The POST method says to use the body portion HTTP request to pass parameters. The same transaction with the POST method would read as follows:

POST /cgi-bin/guestbook.pl HTTP/1.0
...[more headers here]
firstname=Joe&lastname=Grant

Both eyamples,you should recognize the firstname and the lastname variable names that were defined in the HTML form, coupled with the values entered by the user. An ampersand (&) is used to separate to variable=value pairs.

The server now passes the variable=value pairs to the CGI program. It does this either through Unix environment variables or in standard input (STDIN). If the CGI program is called with the GET method parameters are expected to be embedded in the URL of the request, and the server transfers them to the program by assigning them to the QUERY_STRING as it would read any environment variable (for example, from the %ENV associative array in Perl). If the CGI program is called with the POST method, parameters are expected to be embedded into the body of the request, and the server passes the body text to the program as standard input.

The CGI program needs to retrieve the information as appropriate and then process it. The sky is the limit on what the CGI program actually does with the information it retrieves. It might return an anagram of the user's name, or tell them how many times their names use the letter "t", or it might just compile the name into a list that the programmer regularly sells to telemarkets. Only the programmer knows for sure.

Creating Virtual Documents

Regardless of what the CGI programm does with it's input, it's responsible for giving th e browser something to display when it's done. It must create a new document to be served to the browser or point to an existing document. On Unix, programs send their output to the statndard output (STDOUT) as a data stream that consists of two parts. The first part is either full ar partial HTTP header that (at minimum) describes the format of the returned data (i.e., HTML, ASCII text, GIF, etc.) A blank line signifies the end of the header section. The second part is the body of the output, which contains the data conforming to the format type reflected in the header. For example:

Content-type: text/html


<HTML><TITLE>Thanks!</TITLE><HEAD>
<BODY><H1>Thanks for signing my guestbook!</H1>
...
</BODY></HTML>

In this case,the only header line generated is Content-type, which gives the media format of the output as HTML (text/html). This line is essential for every CGI program, since it tells the browser what kind of format to expect. The blank line separates the header from the body text (which, in that case is the HTML format as advertised).

Notice: It does not matter to the web server what language the CGI program is written in . On Unix the most popuar language for CGI programmingis Perl. Other languages used on Unix are C/C++, Tcl, ad Python. On Macintopsh computers, programmers use AppleScript, and C/C++, and on MS Windows, programmers use Visual Basic, Perl, and C/C++. As long as there is a way in a programming language to get data from the server and send data back, you can use it for CGI programming.

The server transfers the result of the CGI program back to the browser. The body text is not modified or interpreted by the server in any way, but the server generally supplies additional headers with information such as the date, the name and version of the server, etc.

CGI programs can also supply a complete header itself, in which case the server does not add any additional headers but instead transfers the response verbatim as returned by the GCI program.

Here's a sample output of a program generating an HTML virtual document,with a complete HTTP header:

HTTP/1.0 200 OK
Date: Tuesday, 03-August-99 11:24:47 GMT
Server: NCSA/1.4.2
Content-type: text/html
Content-length: 2041


<HTML><HEAD><TITLE>Thanks!<TITLE><HEAD>
<BODY>
<H1>Thanks for signing my guestbook!</H1>
...
</BODY></HTML>

The header contains the communication protocol, the date and time of the response, and the server name and version. (The 200 OK is status code generated by the HTTP protocol to communicate the status of a request, in this case successful.) Most importantly, it also contains the content-type and the number of characters (equivalent to the number of bytes) of the enclosed data.

URL Encoding

Befor data supplied on a form can be sent to a CGI program, each form element's name (specified by the name attribute) is equated with the value entered by the user to create a key-value pair. For example, if the user entered "30" when asked for his or her age, the key-value pair would be "age=30". In the transferred data, key-value pairs are separated by the ampersand (&) character.

Since under GET method the form information is sent as part of the URL, form infromation can't include any spaces or other special characters that are not allowed in URLs, and also can't include characters that have other meanings in the URLs, like slashes(/). Therefore the web browser performs some special coding in user-supplied information.

Enocding involves replacing spaces and other special characters in the query string with their hexadecimal equivalents (thus, URL encoding is also sometimes called hexadecimal encoding). Suppose a user fills out and submits a form containing his or her birthday in the sysntax mm/dd/yy (e.g.,11/05/73). The forward slashes in the birthday are among the special characters thaht can't appear in the client's request for the CGI program. Thus, when the browser issues the request, it exncodes the data. The following sample request shows the resulting ecncoding:

POST /cgi-bin/birthday.pl HTTP/1.0
Content-length: 21
birthday=11%2F05%2F73

The squence %2F is actually the hexadecimal equivalent for the slash character.

Extra Path Information

In addition to passing query strings, you can pass additional data, known as extra path information, as part of the URL. Th server gauges where the CGI program name ends; anything following is deemed extra and is stored in the environment variable PATH_INFO. The following line calls a script with extra path information:

http://some.machine/cgi-bin/display.pl/cgi_doc.txt

In this example, we use a script with a .pl suffix to make it clear where the GCI programs path ends and the extra path information begins. Everything after display.pl is the extra path. The PATH_TRANSLATED variable is also set mapping the PATH_INFO to the document root (DOCUMENT_ROOT) directory (i.e., /usr/local/etc/httpd/cgi/cgi_doc.txt).

CGI Environment Variables

Much of the information needed by CGI programs is made available vie UNIX environment variables. Programs can access this information as they would any environment variable (i.e., via the %ENV associative array in Perl). The following table lists the environment variables commonly available through CGI. However, since servers accasionally vary on the names of environment variables the assign, check with your own server documentation for more information.

Environment Variable

Content Returned

AUTH_TYPE

The authentication method used to validate a user. See REMOTE_INDENT and REMOTE_USER.

CONTENT_LENGTH

The length of the query data (in bytes or the number of characters) passed to the CGI program through standard input.

CONTENT_TYPE

The media type of the query data, such as text/html.

DOCUMENT_ROOT

The directory from which web documents are served.

GATEWAY_INTERFACE

The revision of the Common Gateway Interface the server uses.

HTTP_ACCEPT

A list of the media types the client can recept

HTTP_COOKIE

A list of cookies defined for that URL

HTTP_FROM

The email address of the user makeing the query (many browsers do not support this variable).

HTTP_REFERER

The URL of the document the client points to before accessing the CGI program

PATH_INFO

Extra path information passed to a CGI program

PATH_TRANSLATED

The translated version of the path given by the variable PATH_INFO.

QUERY_STRING

The query information passed to the program. It is appended to the URL following a question mark (?).

REMOTE_ADDR

The remote IP address from which the user is making the request.

REMOTE_HOST

The remote hostname from which the user is making the request.

REMOTE_USER

The authenticated name of the user making the query.

REQUEST_METHOD

The method with which the information request was issued (i.e, GET, POST, HEAD).

SCRIPT_NAME

The virtual path (i.e., /cgi-bin/program.pl) of the script being executed.

SERVER_NAME

The sever's host name or IP address.

SERVER_PORT

The port number of the host on which the server is running.

SERVER_PROTOCOL

The name and revision of the information protocol the request came in. with.

SERVER_SOFTWARE

The name and version of the server software that is answering the client request.


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Here's a simple Perl CGI script that uses environment variables to display various information about the server:

#!/usr/bin/perl


print "Content-type: text/html", "\n\n";


print "<HTML>" ,"\n";
print "<HEAD><TITLE>About this Server</TITLE></HEAD>!, "\n";
print "<BODY><H1>About this Server</H1>", "\n";
print "<HR><PRE>";
print "Server Name:        ",$ENV{'SERVER_NAME'}, "<BR>", "\n";
print "Running on Port:    ",$ENV{'SERVER_PORT'}, "<BR>", "\n";
print "Server Software:    ",$ENV{'SERVER_SOFTWARE'}, "<BR>", "\n";
print "Server Protocol:    ",$ENV{'SERVER_PROTOCOL'}, "<BR>", "\n";
print "CGI Revision:       ",$ENV{'GATEWAY_INTERFACE'}, "<BR>", "\n";
print "<HR></PRE>", "\n";
print "</BODY></HTML>", "\n";

exit (0)

The preceding program outputs the content of five environment variables into an HTML document. In Per., you can access the environment variables using the %ENV associative array. Here's a typical output of the program:

<HTML>
<HEAD><TITLE>About this Server</TITLE></HEAD>
<BODY><H1>About this Server</H1>
<HR><PRE>
Server Name:        www.anyserver.com
Running on Port:    80
Server Software:    NCSA/1.4.2
Server Protocol:    HTTP/1.0
CGI Revision   :    CGI/1.1
<HR></PRE>
</BODY></HTML>

 

[ This page was updated: Wednesday, 04-Aug-1999 23:58:34 CET]
Sitemap | Business | Support | Contact L Links
Home | News | WebDesign | Web Hosting L Multimedia L Presentation L Administration
JScript-Intro | Perl-CGI-Intro | VRML-Overview | Security
For information, send email to:
Webmaster
Copyright © 1999 Web Solutions & Technologies
All Rights Reserved. Legal Terms.